const Base = require('./base.js');
const API = require('co-wechat-api');
const fs = require('fs');
const path = require('path');
module.exports = class extends Base {
	constructor(ctx) {
		super(ctx);

		this.mass = this.model("weixin/mass");
		this.conf = this.model("weixin/config");
		this.mass_news = this.model("weixin/mass_news");
		this.mass_send = this.model("weixin/mass_send");
		this.user = this.model("weixin/user");
		

	}
	async indexAction() {
		if(this.isGet) {
			let gets = this.get();
			let wxid = gets.id;
			let wxlist = await this.conf.select();
			if(!wxid && wxlist && wxlist.length > 0) {
				wxid = wxlist[0].id;
			}
			this.assign("wxid", wxid);
			this.assign("wxlist", wxlist);

			return this.display();
		}
		if(this.isPost) {
			let posts = this.post();
			let where = {};

			if(!think.isEmpty(posts.wxid)) {
				where.wxid = posts.wxid;
			}

			if(!think.isEmpty(posts.nickname)) {
				where.nickname = ['like', '%' + posts.nickname + '%'];
			}

			if(!think.isEmpty(posts.content)) {
				where.content = ['like', '%' + posts.content + '%'];
			}

			const data = await this.mass.dataTable(posts, where);
			console.log(data)
			return this.json(data);
		}

	}
	async detailAction() {

		let gets = this.get();
		let mass = await this.mass.findOne(gets.id);
		let sends = await this.mass_send.where({
			mass_id: gets.id
		}).select();
		console.log(sends)
		let news = [];
		if(mass.type == 'news') {
			let newsIds = mass.content.split(",");
			news = await this.mass_news.where({
				id: ['IN', newsIds]
			}).select();

		}
		this.assign("news", news);
		this.assign("sends", sends);
		this.assign("mass", mass);
		return this.display();

	}
	async sendAction() {
		try {
			if(this.isGet) {
				let gets = this.get();
				this.assign("wxid", gets.id);
				return this.display();
			}
			if(this.isPost) {
				let posts = this.post();
				console.log(posts);
				if(!posts.wxid) {
					return this.fail("请配置公众号");
				}

				let openidList = [];
				let user = await this.session("user");
				if(posts.scope == 'all') {
					let openids = await this.user.where({
						wxid: posts.wxid,
						subscribe: 1
					}).field("openid").select();
					openids.forEach((o) => {
						openidList.push(o.openid);
					});
				} else {
					openidList = posts.openids.split(",");
				}
				console.log(openidList);
				let media_id = null;
				let api = await this.wechatApi(posts.wxid);
				if(posts.type == 'news') {
					let newsIds = posts.content.split(",");
					let articles = await this.mass_news.where({
						id: ['IN', newsIds]
					}).select();
					let res = await api.uploadNews({
						articles: articles
					});
					console.log(res);
					media_id = res.media_id;

				}

				let mass_id = await this.mass.add({
					name: posts.name,
					type: posts.type,
					media_id: media_id,
					content: posts.content,
					scope: posts.scope,
					status: 0,
					create_by: user.id,
					create_time: new Date().valueOf(),
					wxid: posts.wxid

				});

				let list = [];
				for(let i = 0; i < openidList.length; i = i + 10000) {
					list.push(openidList.slice(i, i + 10000));
				}
				let listKey = 0;
				for(let i = 0; i < list.length; i++) {

					let data = {};
					if(posts.type == 'news') {
						data = await api.massSendNews(media_id, list[i]);

					} else {
						data = await api.massSendText(posts.content, list[i]);

					}
					console.log(data);
					let body = {
						mass_id: mass_id,
						receivers: list[i].toString(),
						status: data.errcode > 0 ? 2 : 1,
						msg_id: data.msg_id,
						errcode: data.errcode,
						errmsg: data.errmsg,
						created_by: user.id,
						wxid: parseInt(posts.wxid),
						create_time: new Date().valueOf()
					}
					console.log(body);
					await this.mass_send.add(body);

					listKey++;
					if(listKey == list.length || list.length == 0) {
						return this.success("操作成功")
					}

				}

			}
		} catch(e) {
			console.log(e);
		}
	}

	async addNewsAction() {
		if(this.isGet) {
			let gets = this.get();
			await this.session("wxid",gets.id);
			this.assign("wxid", gets.id);
			return this.display();
		}
		if(this.isPost) {

			let posts = this.post();
			let user = await this.session("user");

			let insertId = await this.mass_news.add({

				thumb_media_id: posts.thumb_media_id,
				author: posts.author,
				title: posts.title,
				content_source_url: posts.content_source_url,
				content: posts.content,
				digest: posts.digest,
				show_cover_pic: posts.show_cover_pic,
				create_by: user.user_id,
				create_time: new Date().valueOf(),
				wxid: posts.wxid

			});

			if(think.isEmpty(insertId)) {
				return this.fail("添加失败");
			}

			return this.success("添加成功");

		}
	}
	async newsAction() {

		if(this.isGet) {
			let wxid = this.get("id");
			this.assign("wxid", wxid);
			return this.display();
		}
		if(this.isPost) {

			let posts = this.post();
			let where = {};

			if(!think.isEmpty(posts.wxid)) {
				where.wxid = posts.wxid;
			}

			if(!think.isEmpty(posts.keyword)) {
				where.title = ['like', '%' + posts.keyword + '%'];
			}

			const data = await this.mass_news.dataTable(posts, where);
			console.log(data)
			return this.json(data);

		}

	}

	async selectAction() {

		let gets = this.get();
		this.assign("wxid", gets.id);
		return this.display();

	}
	async deleteNewsAction() {
		let id = this.post("id");

		let rows = await this.mass_news.where({
			id: id
		}).delete();
		if(rows == 0) {
			return this.fail("删除失败")
		}
		return this.success("删除成功")
	}

	async uploadThumbAction() {
		let wxid = this.get("id");

		if(think.isEmpty(wxid)) {
			return this.fail("请配置公众号");
		}

		let file = this.file("picture");

		let pics = await this.uploadImage(file, "weixin");
		let api = await this.wechatApi(wxid);
		let res = await api.uploadMedia(path.join(think.ROOT_PATH,'www',pics[0].url), 'thumb');
		console.log("111111111");
//		res = JSON.parse(res.toString());
		console.log(res);

		return this.success({
			msg: "上传成功",
			media_id:res.thumb_media_id
		});

	}

};